#!/usr/bin/env ruby
require 'xcodeproj'
project_path = './breadwallet.xcodeproj'
$project = Xcodeproj::Project.open(project_path)

$production_id = 'org.voisine.breadwallet'
$development_id = 'com.breadwalet.new'

desired_targets = ['breadwallet', 'breadwallet WatchKit App', 'breadwallet WatchKit Extension', 'MessagesExtension', 'TodayExtension', 'NotificationServiceExtension']
targets = $project.native_targets.select { |target| desired_targets.include? target.name }

targets.each do |target|
  config = target.build_configurations.first
  bundle_id = config.build_settings['PRODUCT_BUNDLE_IDENTIFIER']
  if bundle_id.include? $production_id
    config.build_settings['PRODUCT_BUNDLE_IDENTIFIER'] = bundle_id.gsub($production_id, $development_id)
  elsif bundle_id.include? $development_id
    config.build_settings['PRODUCT_BUNDLE_IDENTIFIER'] = bundle_id.gsub($development_id, $production_id)
  end
end

def toggleWatchTargetCompanionId()
  watch_target = $project.native_targets.find { |target| target.name == 'breadwallet WatchKit App'}
  config = watch_target.build_configurations.first
  plist_path = config.build_settings['INFOPLIST_FILE']
  plist = Xcodeproj::Plist.read_from_path(plist_path)
  companion_bundle_id = plist['WKCompanionAppBundleIdentifier']
  if companion_bundle_id.include? $production_id
    plist['WKCompanionAppBundleIdentifier'] = companion_bundle_id.gsub($production_id, $development_id)
  elsif companion_bundle_id.include? $development_id
    plist['WKCompanionAppBundleIdentifier'] = companion_bundle_id.gsub($development_id, $production_id)
  end
  Xcodeproj::Plist.write_to_path(plist, plist_path)
end

def toggleWatchExtensionId()
  watch_extension_target = $project.native_targets.find { |target| target.name == 'breadwallet WatchKit Extension'}
  config = watch_extension_target.build_configurations.first
  plist_path = config.build_settings['INFOPLIST_FILE']
  plist = Xcodeproj::Plist.read_from_path(plist_path)
  bundle_id = plist['NSExtension']['NSExtensionAttributes']['WKAppBundleIdentifier']
  if bundle_id.include? $production_id
    plist['NSExtension']['NSExtensionAttributes']['WKAppBundleIdentifier'] = bundle_id.gsub($production_id, $development_id)
  elsif bundle_id.include? $development_id
    plist['NSExtension']['NSExtensionAttributes']['WKAppBundleIdentifier'] = bundle_id.gsub($development_id, $production_id)
  end
  Xcodeproj::Plist.write_to_path(plist, plist_path)
end


toggleWatchTargetCompanionId()
toggleWatchExtensionId()
$project.save